package com.wry.wry_test.feign.config;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Author: wangrongyi
 * @Date: 2024/7/24 15:56
 * @Description: 轮询算法
 */
@Slf4j
public class RoundRobin implements LoadBalanceService {
    private final LoadBalanceProperties properties;

    public RoundRobin(LoadBalanceProperties loadBalanceProperties) {
        this.properties = loadBalanceProperties;
    }

    private final AtomicInteger index = new AtomicInteger(0);

    @Override
    public synchronized String getServerAddress() {
        if (properties.getAddress().isEmpty()) {
            throw new RuntimeException("服务地址为空");
        }
        int i = index.get() % properties.getAddress().size();
        index.set((i + 1) % properties.getAddress().size());
        return properties.getAddress().get(i);
    }
}
